import React, {useEffect, useRef, useState} from 'react';
import type {ActionType, ProColumns, ProFormInstance} from '@ant-design/pro-components';
import {ProForm, ProTable} from '@ant-design/pro-components';
import {Modal, Button, Form, Select, message} from 'antd';
import {
  empowerOrRevokeUsingPost,
  listRoleVosByUserIdUsingPost, listUserExRolesUsingPost
} from '@/services/easyapi/eUserCenter';
import {from} from "stylis";

export enum UserOperationActions {
  BIND_USER = "bindUser",
  LIFT_USER = "liftUser",
  EMPOWER_USER = "empowerUser",
  REVOKE_USER = "revokeUser",
}

export type Props = {
  user: API.ApiCenterUserVo;
  visible: boolean;
  onCancel: () => void;
};

const initialData: API.RoleVo[] = [];

const EmpowerOrRevoke: React.FC<Props> = (props) => {
  const {visible, onCancel, user} = props;
  const formRef = useRef<ProFormInstance<any>>();
  const [dataSource, setDataSource] = useState<API.RoleVo[]>(initialData);
  const [isAddModalVisible, setAddModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [options, setOptions] = useState<API.RoleVo[]>([]);
  const actionRef = useRef<ActionType>();
  useEffect(() => {
    if (visible) {
      // Fetch user roles when the modal becomes visible
      listRoleVosByUserIdUsingPost({
        userId: user.id
      }).then((res) => {
        setDataSource(res.data || []); // Set the data source to the response data
      });
    }
  }, [visible]);

  const columns: ProColumns<API.RoleVo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      width: '30%',
    },
    {
      title: '角色描述',
      dataIndex: 'roleDesc',
      width: '50%',
    },
    {
      title: '操作',
      valueType: 'option',
      width: '20%',
      render: (_, record) => {
        // Check if the user is an admin
        const isAdmin = record.roleName === 'admin';
        const isVisitor = record.roleName==='visitor'
        // Do not show the "取消授权" button if the user is an admin
        if (!isAdmin && !isVisitor ) {
          return (
            <Button
              type="link"
              danger
              //@ts-ignore
              onClick={() => handleRevoke(user.id, record.id)}
            >
              取消授权
            </Button>
          );
        }
        return null;
      },
    },
  ];

  const listRoleVo = async () => {
    const res = await listUserExRolesUsingPost({
      userId: user.id
    });
    setOptions(
      // @ts-ignore
      res.data.map((role) => ({
        label: role.roleName,
        value: role.id,
      })) || []
    );
  };

  const handleAdd = async () => {
    const roleId = await form.validateFields();
    await empowerOrRevokeUsingPost({
      userId: user.id,
      roleId: roleId.id,
      action:UserOperationActions.EMPOWER_USER
    }).then(res=>{
      if (res.code===200){
        message.success("添加成功!")
        setAddModalVisible(false)
        listRoleVosByUserId()
      }
      console.log(res)
    })
    form.resetFields();
  };

  const handleRevoke = async (id:number, roleId:number) => {
    await empowerOrRevokeUsingPost({
      userId: id,
      roleId: roleId,
      action: UserOperationActions.REVOKE_USER
    }).then(res => {
     if (res.code===200){
       message.success('取消授权成功');
     } else {
       message.error(res.msg)
     }
    })
    listRoleVosByUserId()
  };

  const listRoleVosByUserId = async ()=>{
   await  listRoleVosByUserIdUsingPost({
      userId: user.id
    }).then((res) => {
      setDataSource(res.data || []); // Set the data source to the response data
    });
  }

  return (
    <>
      <Modal width="50%" visible={visible} footer={null} onCancel={onCancel}>
        <ProForm<{
          table: API.RoleVo[];
        }>
          formRef={formRef}
          initialValues={{
            table: dataSource,
          }}
          validateTrigger="onBlur"
          submitter={false} // Disable the submit button and other controls
        >
          <ProTable<API.RoleVo>
            rowKey="id"
            scroll={{
              x: 500,
            }}
            actionRef={actionRef}
            //@ts-ignore
            request={listRoleVosByUserId}
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            search={false}
            toolBarRender={() => [
              <Button
                type="primary"
                onClick={()=>{
                  listRoleVo()
                  setAddModalVisible(true)
                }} // Updated to call handleAdd
              >
                新增授权
              </Button>,
            ]}
          />
        </ProForm>
      </Modal>

      <Modal
        title="授予角色..."
        visible={isAddModalVisible}
        onCancel={() => setAddModalVisible(false)}
        onOk={() => form.submit()}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleAdd}
        >
          <Form.Item
            name="id"
            label="角色"
            rules={[{required: true, message: '角色为必填项'}]}
          >
            <Select
              options={options}
              placeholder="请选择角色"
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default EmpowerOrRevoke;
